// pages/statistics/statistics.js
Page({
  data: {
    // 图表数据
    chartData: [],
    timeRange: 'week', // week, month, year
    currentPeriodText: '',
    
    // 统计指标
    avgSystolic: 0,
    avgDiastolic: 0,
    complianceRate: 0,
    unit: 'mmHg',
    
    // 用药依从性
    medicationCompliance: 0,
    totalMedicationDays: 0,
    onTimeDays: 0,
    missedDays: 0,
    
    // 健康建议
    healthTips: [],
    
    // 无数据状态
    noData: false
  },

  onLoad() {
    // 获取单位设置
    const settings = wx.getStorageSync('settings') || {};
    const unit = settings.bloodPressureUnit || 'mmHg';
    
    this.setData({
      unit: unit
    });
    
    // 加载统计数据
    this.loadStatisticsData();
    
    // 监听存储变化
    wx.onStorageChange(this.handleStorageChange);
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadStatisticsData();
  },

  onUnload() {
    // 页面卸载时移除监听
    wx.offStorageChange(this.handleStorageChange);
  },

  // 切换时间范围
  changeTimeRange(e) {
    const range = e.currentTarget.dataset.range;
    
    this.setData({
      timeRange: range
    }, () => {
      this.loadStatisticsData();
    });
  },

  // 加载统计数据
  loadStatisticsData() {
    const { timeRange } = this.data;
    
    // 获取血压记录
    const bloodRecords = wx.getStorageSync('bloodPressureRecords') || [];
    // 获取用药记录
    const medicationRecords = wx.getStorageSync('medicationRecords') || [];
    
    // 检查是否有数据
    if (bloodRecords.length === 0 && medicationRecords.length === 0) {
      this.setData({
        noData: true
      });
      return;
    }
    
    this.setData({
      noData: false
    });
    
    // 根据时间范围筛选数据
    const filteredBloodRecords = this.filterRecordsByTimeRange(bloodRecords, timeRange);
    const filteredMedicationRecords = this.filterRecordsByTimeRange(medicationRecords, timeRange);
    
    // 更新当前周期文本
    this.updateCurrentPeriodText(timeRange);
    
    // 处理血压数据
    if (filteredBloodRecords.length > 0) {
      this.processBloodPressureData(filteredBloodRecords);
    }
    
    // 处理用药数据
    if (filteredMedicationRecords.length > 0) {
      this.processMedicationData(filteredMedicationRecords);
    }
    
    // 生成健康建议
    this.generateHealthTips(filteredBloodRecords, filteredMedicationRecords);
  },

  // 根据时间范围筛选记录
  filterRecordsByTimeRange(records, timeRange) {
    const now = new Date();
    let startDate = new Date();
    
    // 根据时间范围设置起始日期
    switch (timeRange) {
      case 'week':
        startDate.setDate(now.getDate() - 6); // 过去7天
        break;
      case 'month':
        startDate.setMonth(now.getMonth() - 1); // 过去30天
        break;
      case 'year':
        startDate.setFullYear(now.getFullYear() - 1); // 过去1年
        break;
    }
    
    // 筛选记录
    return records.filter(record => {
      const recordDate = new Date(record.recordTime);
      return recordDate >= startDate && recordDate <= now;
    });
  },

  // 更新当前周期文本
  updateCurrentPeriodText(timeRange) {
    const now = new Date();
    let periodText = '';
    
    switch (timeRange) {
      case 'week':
        const weekStart = new Date(now);
        weekStart.setDate(now.getDate() - 6);
        periodText = `${this.formatDate(weekStart, 'MM-DD')} - ${this.formatDate(now, 'MM-DD')}`;
        break;
      case 'month':
        periodText = `${now.getFullYear()}年${now.getMonth() + 1}月`;
        break;
      case 'year':
        periodText = `${now.getFullYear()}年`;
        break;
    }
    
    this.setData({
      currentPeriodText: periodText
    });
  },

  // 处理血压数据
  processBloodPressureData(records) {
    if (records.length === 0) return;
    
    // 提取收缩压和舒张压数据
    const systolicValues = records.map(record => record.systolic);
    const diastolicValues = records.map(record => record.diastolic);
    
    // 计算平均值
    const avgSystolic = Math.round(this.average(systolicValues));
    const avgDiastolic = Math.round(this.average(diastolicValues));
    
    // 计算达标率（收缩压<=130且舒张压<=85）
    const normalCount = records.filter(record => 
      record.systolic <= 130 && record.diastolic <= 85
    ).length;
    
    const complianceRate = Math.round((normalCount / records.length) * 100);
    
    // 格式化图表数据
    const chartData = records.map(record => ({
      date: record.recordTime.split(' ')[0],
      systolic: record.systolic,
      diastolic: record.diastolic,
      recordTime: record.recordTime
    }));
    
    this.setData({
      avgSystolic: avgSystolic,
      avgDiastolic: avgDiastolic,
      complianceRate: complianceRate,
      chartData: chartData
    });
  },

  // 处理用药数据
  processMedicationData(records) {
    if (records.length === 0) return;
    
    // 计算总天数（去重）
    const uniqueDates = [...new Set(records.map(record => 
      record.recordTime.split(' ')[0]
    ))];
    
    const totalDays = uniqueDates.length;
    
    // 计算按时服药天数
    const onTimeCount = records.filter(record => 
      record.status === 'taken'
    ).length;
    
    // 计算未按时服药天数
    const missedCount = totalDays - onTimeCount;
    
    // 计算服药依从性
    const compliance = totalDays > 0 ? Math.round((onTimeCount / totalDays) * 100) : 0;
    
    this.setData({
      medicationCompliance: compliance,
      totalMedicationDays: totalDays,
      onTimeDays: onTimeCount,
      missedDays: missedCount
    });
  },

  // 生成健康建议
  generateHealthTips(bloodRecords, medicationRecords) {
    const tips = [];
    
    // 血压相关建议
    if (bloodRecords.length > 0) {
      const avgSystolic = this.data.avgSystolic;
      const avgDiastolic = this.data.avgDiastolic;
      
      if (avgSystolic > 130 || avgDiastolic > 85) {
        tips.push('您的血压偏高，建议减少盐分摄入，增加有氧运动。');
      }
      
      if (bloodRecords.length < 5) {
        tips.push('血压数据不足，建议每天固定时间测量并记录。');
      }
    }
    
    // 用药相关建议
    if (medicationRecords.length > 0) {
      const compliance = this.data.medicationCompliance;
      
      if (compliance < 80) {
        tips.push(`您的用药依从性为${compliance}%，请尽量按时服药以控制血压。`);
      } else {
        tips.push('您的用药依从性良好，请继续保持！');
      }
    }
    
    // 通用健康建议
    if (tips.length === 0) {
      tips.push('您的血压控制良好，用药依从性高，继续保持健康生活方式！');
    }
    
    tips.push('建议保持规律作息，避免过度劳累和情绪波动。');
    tips.push('饮食宜清淡，多食用蔬菜水果，控制体重。');
    
    this.setData({
      healthTips: tips
    });
  },

  // 处理存储变化
  handleStorageChange(e) {
    if (e.key === 'bloodPressureRecords' || e.key === 'medicationRecords') {
      this.loadStatisticsData();
    }
  },

  // 计算平均值
  average(arr) {
    return arr.reduce((sum, val) => sum + val, 0) / arr.length;
  },

  // 格式化日期
  formatDate(date, format) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    
    if (format === 'MM-DD') {
      return `${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
    }
    
    return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
  }
})